package main

import (
	"log"
	"context"
	pb "learngo/consignment-service/proto/consignment"
	vesselProto "learngo/vessel-service/proto/vessel"
	"gopkg.in/mgo.v2"
)

type service struct {
	session *mgo.Session
	// 请注意，我们在这里记录了一个货船服务的客户端对象
	vesselClient vesselProto.VesselServiceClient

}

func (s *service)getRepo() Repository  {
	return &ConsignmentRepository{s.session.Clone()}
}

func (s *service) CreateConsignment(ctx context.Context, req *pb.Consignment, res *pb.Response) error {

	repo := s.getRepo()
	defer repo.Close()

	// 这里，我们通过货船服务的客户端对象，向货船服务发出了一个请求
	vesselResponse, err := s.vesselClient.FindAvailable(context.Background(), &vesselProto.Specification{
		MaxWeight: req.Weight,
		Capacity:  int32(len(req.Containers)),
	})

	log.Printf("Found vessel: %s \n", vesselResponse.Vessel.Name)

	req.VesselId = vesselResponse.Vessel.Id
	err = repo.Create(req)
	if err != nil {
		return err
	}
	res.Created = true
	res.Consignment = req

	return nil
}

func (s *service) GetConsignments(ctx context.Context, req *pb.GetRequest, res *pb.Response) error {
	repo := s.getRepo()
	defer repo.Close()

	consignments,err := repo.GetAll()

	if err != nil {
		return err
	}
	res.Consignments = consignments
	return nil
}
